<template>
	<view class="answer-container">
		<!-- 作业内容展示 -->
		<view class="homework-content">
			<textarea class="content-display" :value="homeworkContent" disabled auto-height :maxlength="-1"></textarea>
		</view>

		<!-- 作答区域 -->
		<view class="answer-area">
			<textarea :disabled="isSubmitButtonDisabled" class="answer-input" v-model="answerForm.content"
				placeholder="请输入答案" auto-height :maxlength="-1"></textarea>
			<!-- 上传文件回显区域 -->
			<view class="image-file-preview" v-if="uploadedImageFiles.length > 0">
				<view v-for="(image, index) in uploadedImageFiles" :key="index" class="image-file-item">
					<image :src="image.url" mode="aspectFill"></image>
					<text class="delete-icon" @click="handleDeleteImageFile(index,image)"
						v-if="!isSubmitButtonDisabled">x
					</text>
				</view>
			</view>
			<view class="file-preview" v-if="uploadedFiles.length > 0">
				<view v-for="(file, index) in uploadedFiles" :key="index" class="file-item">
					<image class="file-icon" src="/static/FileIcon.png"></image>
					<text>{{file.fileName}}</text>
					<text class="delete-icon" @click="handleDeleteFile(index,file)" v-if="!isSubmitButtonDisabled">x
					</text>
				</view>
			</view>
		</view>

		<view class="submit-btn-container">
			<button class="submit-btn" @tap="handleUploadClick" :disabled="isSubmitButtonDisabled"
				:class="{'submit-btn-enabled':!isSubmitButtonDisabled, 'submit-btn-disabled': isSubmitButtonDisabled}">
				上传文件
			</button>
			<xe-upload ref="xeUploadRef" :options="uploadOptions" @callback="handleUploadCallback"></xe-upload>
		</view>
		<!-- 提交按钮 -->
		<view class="submit-btn-container">
			<button class="submit-btn" @tap="handleSubmit" :disabled="isSubmitButtonDisabled"
				:class="{'submit-btn-enabled':!isSubmitButtonDisabled, 'submit-btn-disabled': isSubmitButtonDisabled}">
				提交
			</button>
		</view>

		<!-- 教师反馈 -->
		<view class="teacher-feedback" v-if="RequestAnswerResForm.isRead!== null && RequestAnswerResForm.isRead === 1">
			<text class="feedback-title">专家批阅</text>
			<view class="feedback-divider"></view>
			<view class="feedback-content">{{RequestAnswerResForm.comment }}</view>
			<view class="feedback-meta">
				<text>时间:{{formatDate(RequestAnswerResForm.readDate) }}</text>
				<text>得分:{{RequestAnswerResForm.score }}</text>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		onMounted,
		reactive,
		ref,
		watch
	} from 'vue';
	import {
		onLoad
	} from '@dcloudio/uni-app';
	import {
		apiSubmitHomeWork,
		apiGetHomeWorkDetail,
		apiUploadFiles,
		apiDeleteFiles,
		apiUploadFile
	} from '../../api/apis';




	// 作业内容
	const homeworkContent = ref("");
	// 用户作答内容
	const answer = ref("");
	// 上传的图片文件数组
	const uploadedImageFiles = ref([]);
	// 上传的其他文件数组
	const uploadedFiles = ref([]);
	// const uploadedImages = ref([]);
	// 回答作业的表单
	const answerForm = reactive({
		homeworkId: null,
		studentId: null,
		content: null,
	})
	// 回显数据用来展示数据的表单
	const RequestAnswerResForm = reactive({
		isRead: null,
		score: null,
		comment: null,
		readDate: null,
		content: null,
		endDate: null,
	})
	// 请求回显数据的请求体表单
	const RequestAnswerForm = reactive({
		homeworkId: null,
		studentId: null,
	})
	const deleteFileForm = reactive({
		homeworkId: null,
		studentId: null,
		fileName: '',
	})

	// 新增响应式数据用于判断提交按钮是否禁用，初始值根据已有逻辑先设置
	// 定义一个 ref 用于存储是否禁用提交按钮的状态
	const isSubmitButtonDisabled = ref(false);
	const token = ref("");
	// 使用 watch 监听 RequestAnswerResForm.endDate 的变化
	watch(() => RequestAnswerResForm.endDate, (newEndDate) => {
		console.log(newEndDate);
		if (newEndDate) {
			// 获取当前时间
			const currentDate = new Date();
			// 将 endDate 字符串转换为 Date 对象
			const endDateTime = new Date(newEndDate);
			// 比较当前时间和 endDate
			if (currentDate > endDateTime) {
				isSubmitButtonDisabled.value = true;
			} else {
				console.log(RequestAnswerResForm.isRead);
				isSubmitButtonDisabled.value = RequestAnswerResForm.isRead === 1;
			}
		}

	}, {
		immediate: true
	});


	// 定义响应式数据，直接置空表示仅读取不发送
	const uploadOptions = ref({

	});

	// 引用组件
	const xeUploadRef = ref(null);

	// 处理上传点击事件，这里先从手机读取文件到软件本地
	const handleUploadClick = () => {
		xeUploadRef.value.upload('file', {});

	};

	// 处理上传回调事件

	var uploadnum = 0; // 上传的文件数
	var successNum = 0; // 成功的文件数
	var failNum = 0; // 失败的文件数
	const handleUploadCallback = async (e) => {
		uni.showLoading({
			title: '正在上传…'
		});
		successNum = 0; // 成功的文件数
		failNum = 0; // 失败的文件数
		if (e.type == 'success' || e.type == 'choose') {

			console.log(e);
			uploadnum = e.data.length;

			e.data.forEach(data => {

				if (data.fileType === "image") {
					const image = {
						url: data.tempFilePath, // 本地预览地址
						status: 'loadFromLocal' // 状态
					};
					uploadedImageFiles.value.push(image);
					uploadImage(image)
				} else {
					let file = {
						fileName: data.name,
						primevalName: '',
						localUrl: data.tempFilePath,
						status: 'loading'
					}
					uploadedFiles.value.push(file);
					console.log(file.fileName, file.localUrl)
					uploadFile(file);
				}

			})

		} else if (e.type == 'warning') {
			console.log("选择文件失败");
			uni.hideLoading();
			uni.showToast({
				title: '标题',
				icon: 'error'
			});
		}
	};

	// 向网络发送图片的请求
	const uploadImage = async (image) => {
		try {
			const response = await apiUploadFile({
				filePath: image.url,
				studentId: Number(answerForm.studentId),
				homeWorkId: Number(answerForm.homeworkId)
			});

			// 上传成功后的逻辑
			image.status = 'success';
			image.netUrl = response;
			const index = uploadedImageFiles.value.findIndex(img => img.url === image.url);
			if (index !== -1) {
				uploadedImageFiles.value[index] = {
					...image
				};
				cacheImage(response); // 缓存图片
			}
			console.log("图片上传成功");
			successNum++;
		} catch (error) {
			console.error('图片上传失败:', error);
			const index = uploadedImageFiles.value.findIndex(img => img.url === image.url);
			if (index !== -1) {
				uploadedImageFiles.value.splice(index, 1);
			}
			failNum++;
		} finally {
			uploadnum--;
			allUploaded();
		}
	};

	// 向网络发送文件的请求
	const uploadFile = async (file, studentId, homeWorkId) => {
		try {
			const response = await apiUploadFile({
				filePath: file.localUrl,
				studentId: Number(answerForm.studentId),
				homeWorkId: Number(answerForm.homeworkId)
			});

			// 上传成功后的逻辑
			file.status = 'success';
			file.primevalName = response;
			const index = uploadedFiles.value.findIndex(filei => filei.localUrl === file.localUrl);
			if (index !== -1) {
				uploadedFiles.value[index] = {
					...file
				};
			}
			successNum++;
		} catch (error) {
			console.error('文件上传失败:', error);
			const index = uploadedFiles.value.findIndex(filei => filei.localUrl === file.localUrl);
			if (index !== -1) {
				uploadedFiles.value.splice(index, 1);
			}
			failNum++;
		} finally {
			uploadnum--;
			allUploaded();
		}
	};


	// 将图片缓存到本地
	const cacheImage = (imageUrl) => {
		// 将保存的文件路径缓存到本地存储
		const cacheKey = `image_${imageUrl}`; // 使用 imageUrl 作为缓存键
		if (uni.getStorageSync(cacheKey)) return; // 已缓存则跳过
		// 先下载图片到本地临时文件
		uni.downloadFile({
			url: imageUrl, // 网络图片路径
			success: (downloadRes) => {
				if (downloadRes.statusCode === 200) {
					const tempFilePath = downloadRes.tempFilePath; // 获取临时文件路径

					// 将临时文件保存到本地
					uni.saveFile({
						tempFilePath: tempFilePath,
						success: (saveRes) => {
							const savedFilePath = saveRes.savedFilePath; // 获取保存后的文件路径
							uni.setStorageSync(cacheKey, savedFilePath);

							console.log('图片缓存成功:', savedFilePath);
						},
						fail: (err) => {
							console.error('保存图片失败:', err);
						}
					});
				} else {
					console.error('下载图片失败，状态码:', downloadRes.statusCode);
				}
			},
			fail: (err) => {
				console.error('下载图片失败:', err);
			}
		});
	};

	const allUploaded = () => {
		if (uploadnum === 0) {
			uni.hideLoading();
			if (successNum === 0) {
				uni.showToast({
					title: '上传失败',
					icon: 'error'
				});
			} else {
				if (failNum === 0) {
					uni.showToast({
						title: '上传成功',
						icon: 'success'
					});
				} else {
					uni.showToast({
						title: successNum + '个成功，' + failNum + '个失败',
						icon: 'none'
					});
				}
			}
		}
	}

	onLoad((options) => {
		// 获取路由参数
		homeworkContent.value = decodeURIComponent(options.title);
		answerForm.homeworkId = `${options.id}`;
		deleteFileForm.homeworkId = `${options.id}`;
		RequestAnswerForm.homeworkId = `${options.id}`;
		console.log(homeworkContent.value)
		// 获取本地学生数据缓存
		uni.getStorage({
			key: 'studentInfo',
			success: async function(res) {
				const studentVO = res.data;
				answerForm.studentId = studentVO.id;
				deleteFileForm.studentId = studentVO.id;;
				RequestAnswerForm.studentId = studentVO.id;
				const result = await apiGetHomeWorkDetail(RequestAnswerForm);
				if (result.code === 0) {
					uploadedImageFiles.value = [];
					const ResData = result.data;
					console.log(ResData)
					RequestAnswerResForm.comment = ResData.comment;
					RequestAnswerResForm.isRead = ResData.isRead;
					RequestAnswerResForm.score = ResData.score;
					RequestAnswerResForm.readDate = ResData.readDate;
					RequestAnswerResForm.endDate = ResData.endDate;
					for (let i = 0; i < ResData.imageUrls.length; i++) {
						const imageUrl = ResData.imageUrls[i];
						const cachedImagePath = uni.getStorageSync(`image_${imageUrl}`);
						if (cachedImagePath) {
							// 如果本地缓存中有图片，直接使用缓存
							uploadedImageFiles.value.push({
								url: cachedImagePath, // 本地缓存地址
								netUrl: imageUrl,
								status: 'loadFromLocal' // 状态
							});
						} else {
							// 如果本地缓存中没有图片，从服务器获取
							uploadedImageFiles.value.push({
								url: imageUrl, // 本地预览地址
								netUrl: imageUrl,
								status: 'loading' // 状态
							});
						}
					}
					for (let i = 0; i < ResData.fileNames.length; i++) {
						console.log(ResData.fileNames[i]);
						uploadedFiles.value.push(handleUrlFile({
							fileName: ResData.fileNames[i],
							primevalName: ResData.fileNames[i],
							status: 'success',
							localUrl: ''
						}));
					}
					console.log(ResData)
					answerForm.content = ResData.content;
				}

			},
		});
	});

	// 对文件的名称进行处理，删去uuid
	const handleUrlFile = (file) => {
		try {

			let fileName = file.fileName.substring(file.fileName.lastIndexOf('/') + 1);

			// 使用正则表达式去除 UUID（假设是标准格式）和时间戳（假设是以 "-" 分隔的纯数字）
			fileName = fileName.replace(/^[\da-f]{8}-([\da-f]{4}-){3}[\da-f]{12}_/, '') // 去掉 UUID 和前面的下划线
				.replace(/-\d+\./, '.'); // 去掉时间戳（保留文件后缀）

			console.log(fileName);
			file.fileName = fileName;
			return file;
		} catch (error) {
			console.error('无效的 URL:', error);
			return null;
		}
	}

	// 删除图片的方法
	const handleDeleteImageFile = (index, image) => {
		uni.showModal({
			title: '确认删除',
			content: '是否确认删除这个图片？',
			success: async (res) => {
				if (res.confirm) {
					// 显示删除的加载框
					uni.showLoading({
						title: '正在删除…'
					});
					deleteFileForm.fileName = image.netUrl;
					try {
						let modelRes = await apiDeleteFiles(deleteFileForm);
						if (modelRes.code === 0) {
							uploadedImageFiles.value.splice(index, 1);
							// 2. 删除本地缓存
							const cacheKey = `image_${image.netUrl}`;
							uni.removeStorageSync(cacheKey);
							
							uni.hideLoading();
							uni.showToast({
								title: '删除成功',
								icon: 'success'
							});
						} else {
							uni.hideLoading();
							uni.showToast({
								title: '删除失败',
								icon: 'error'
							});
						}
						console.log(modelRes)
					} catch (error) {
						uni.hideLoading();
						console.error('删除图片时发生错误:', error);
						uni.showToast({
							title: '删除失败',
							icon: 'error'
						});
					}
				}
			}
		});
	};

	// 删除文件的方法
	const handleDeleteFile = (index, file) => {
		uni.showModal({
			title: '确认删除',
			content: '是否确认删除这个文件？',
			success: async (res) => {
				if (res.confirm) {
					// 弹出删除图片的提示
					uni.showLoading({
						title: '正在删除…'
					});
					deleteFileForm.fileName = file.primevalName;
					console.log(deleteFileForm.fileName);
					try {
						let modelRes = await apiDeleteFiles(deleteFileForm);
						console.log(typeof modelRes);
						if (modelRes.code === 0) {
							uploadedFiles.value.splice(index, 1);
							uni.hideLoading();
							uni.showToast({
								title: '删除成功',
								icon: 'success'
							});

						} else {
							uni.hideLoading();
							uni.showToast({
								title: '删除失败',
								icon: 'error'
							});
						}
						console.log(modelRes);
					} catch (error) {
						uni.hideLoading();
						console.error('删除文件时发生错误:', error);
						uni.showToast({
							title: '删除失败',
							icon: 'error'
						});
					}
				}
			}
		});
	};
	// 提交作答方法
	const handleSubmit = async () => {
		if (answerForm.content.trim() === "") {
			uni.showToast({
				title: "作答内容不能为空",
				icon: "none",
				duration: 2000,
			});
			return;
		}

		let res = await apiSubmitHomeWork(answerForm);
		if (res.code === 0) {
			uni.showToast({
				title: "提交成功",
				icon: "success",
				duration: 1000,
			});
			// 等待提示框展示完成后重新加载页面
			setTimeout(() => {
				uni.redirectTo({
					url: "/pages/homework/homework", // 替换为当前页面的路径
				});
			}, 1000);
		}
	};

	// Methods
	const formatDate = (date) => {
		if (!date) return '暂无';
		return new Date(date).toLocaleString('zh-CN', {
			year: 'numeric',
			month: '2-digit',
			day: '2-digit',
			hour: '2-digit',
			minute: '2-digit'
		});
	};
</script>

<style lang="scss" scoped>
	.answer-container {
		min-height: 100vh;
		background: rgba(245, 247, 250, 0.98);
		backdrop-filter: blur(10px);
		padding: 20rpx;
		padding-top: calc(var(--status-bar-height, 44px) + 20rpx);
	}

	.homework-content {
		margin-bottom: 40rpx;

		.content-display {
			width: 94%;
			min-height: 120rpx;
			border-radius: 12rpx;
			padding: 20rpx;
			font-size: 28rpx;
			color: #666;
			background-color: #f8f9fa;
			line-height: 1.6;
		}
	}

	.answer-area {
		margin-bottom: 40rpx;

		.answer-input {
			width: 94%;
			min-height: 240rpx;
			border: 1rpx solid #e0e0e0;
			border-radius: 12rpx;
			padding: 20rpx;
			font-size: 28rpx;
			color: #333;
			background-color: #fff;
			line-height: 1.6;

			&:disabled {
				background-color: #f5f5f5;
				color: #999;
			}
		}
	}

	.image-preview {
		margin-top: 20rpx;
		padding: 0 20rpx;

		.image-item {
			margin-bottom: 20rpx;
			position: relative;

			.preview-image {
				width: 100%;
				border-radius: 8rpx;
			}

			.image-label {
				position: absolute;
				top: 10rpx;
				left: 10rpx;
				background: rgba(0, 0, 0, 0.5);
				color: white;
				padding: 4rpx 8rpx;
				border-radius: 4rpx;
				font-size: 24rpx;
			}
		}
	}

	.submit-btn-container {
		margin: 40rpx 0;
		padding: 0 40rpx;
	}

	.submit-btn {
		width: 100%;
		height: 88rpx;
		border-radius: 44rpx;
		font-size: 32rpx;
		font-weight: 600;

		&.submit-btn-enabled {
			background: linear-gradient(135deg, #2196F3, #1976D2);
			color: #ffffff;
			box-shadow: 0 4rpx 12rpx rgba(33, 150, 243, 0.2);

			&:active {
				transform: scale(0.98);
				opacity: 0.9;
			}
		}

		&.submit-btn-disabled {
			background-color: #e0e0e0;
			color: #999;
		}
	}

	.teacher-feedback {
		background: #fff;
		border-radius: 12rpx;
		padding: 24rpx;
		margin-top: 20rpx;

		.feedback-title {
			font-size: 32rpx;
			font-weight: 600;
			color: #333;
		}

		.feedback-divider {
			height: 1rpx;
			background: #f0f0f0;
			margin: 16rpx 0;
		}

		.feedback-content {
			font-size: 28rpx;
			color: #666;
			line-height: 1.6;
			margin-bottom: 20rpx;
		}

		.feedback-meta {
			display: flex;
			justify-content: space-between;
			font-size: 24rpx;
			color: #999;
		}
	}

	.image-file-preview {
		margin-top: 10px;
		display: grid;
		grid-template-columns: repeat(auto-fit, minmax(80px, 1fr));
		/* 最小宽度80px，最大填满 */
		gap: 8px;
		/* 图片之间的间距 */

	}

	.image-file-item {
		position: relative;
		width: 100%;
		aspect-ratio: 1;
		border: 1px solid #e0e0e0;
		border-radius: 8px;
		overflow: hidden;

		/* 图片主体 */
		image {
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
			object-fit: cover;
		}

		/* 调暗图片 */
		.image-uploading {
			filter: brightness(0.5); // 调暗图片
		}

		/* 遮罩层 */
		.upload-overlay {
			position: absolute;
			top: 50%;
			/* 居中 */
			left: 50%;
			/* 居中 */
			transform: translate(-50%, -50%);
			/* 精确居中 */
			width: 40px;
			/* 根据需要调整大小 */
			height: 40px;
			z-index: 10;
			/* 确保图标在其他元素之上 */
			pointer-events: none;
			/* 避免干扰点击操作 */

		}

		/* 加载动画 */
		.loading-spinner {
			width: 100%;
			height: 100%;
			animation: spin 1s linear infinite;
			/* 只在内部旋转 */
		}

		@keyframes spin {
			from {
				transform: rotate(0deg);
			}

			to {
				transform: rotate(360deg);
			}
		}

	}

	/* 居中显示文字 */
	.image-file-item .status-text {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		color: #ffffff;
		font-size: 14px;
		font-weight: bold;
		z-index: 2;
	}

	/* 删除按钮 */
	.delete-icon {
		position: absolute;
		top: 5px;
		right: 5px;
		width: 20px;
		height: 20px;
		background-color: rgba(0, 0, 0, 0.5);
		color: #fff;
		border-radius: 50%;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 14px;
		cursor: pointer;
		z-index: 3;
	}

	.delete-icon {
		cursor: pointer;
		font-size: 32rpx;
		color: #999;
		transition: color 0.3s ease;
	}

	.file-preview {
		display: flex;
		flex-direction: column;
		gap: 8px;
		margin-top: 10px;
	}

	.file-item {
		display: flex;
		flex-direction: row;
		/* 横向排列 */
		align-items: center;
		/* 垂直居中对齐 */
		width: 100%;
		max-width: 400px;
		padding: 12px;
		padding-right: 30px;
		height: auto;
		border: 1px solid #e0e0e0;
		border-radius: 8px;
		background-color: #fafafa;
		// box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
		overflow: hidden;
		position: relative;
		/* 新增 */
	}

	.file-icon {
		width: 40px;
		/* 固定宽度 */
		height: 40px;
		/* 固定高度 */
		margin-right: 10px;
		/* 与文字之间的间隔 */
		flex-shrink: 0;
		/* 防止被压缩 */
	}

	.file-item text:first-child {
		flex: 1;
		/* 占满剩余空间 */
		font-size: 14px;
		color: #333;
		line-height: 1.5;
		white-space: normal;
		overflow: hidden;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 2;
	}

	.status-text {
		font-size: 12px;
		color: #999;
		margin-left: 4px;
	}

	.delete-icon {
		position: absolute;
		top: 6px;
		right: 6px;
		width: 20px;
		height: 20px;
		background-color: rgba(0, 0, 0, 0.5);
		color: #fff;
		border-radius: 50%;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 14px;
		cursor: pointer;
		z-index: 2;
	}
</style>